package com.asm.repository;

import com.asm.entity.sys.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author ZhuangGuiMan
 * @description 定义用户操作的接口
 * @date 2019/7/12
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    /**
     * 根据用户编号查找用户
     *
     * @param id 用户编号
     * @return 用户
     */
    @Query("select u from User u where u.id=:id and u.isDel=false ")
    User findUserById(@Param("id") Long id);

    /**
     * 根据账号和密码查询用户
     *
     * @param account  用户账号
     * @param password 密码
     * @param isDel 是否被删除
     * @return 用户
     */
    User findUserByAccountAndPasswordAndIsDel(String account, String password, Boolean isDel);

    /**
     * 根据账号和手机确认用户
     *
     * @param account 账号
     * @param phone 手机
     * @param isDel 是否被删除
     * @return 用户
     */
    User findByAccountAndPhoneAndIsDel(String account, String phone, Boolean isDel);

    /**
     * 根据用户编号查询预定信息
     *
     * @param userId   用户编号
     * @param pageable 分页
     * @return 预定信息
     */
    @Query("select new Map(b.id as bookId,cc.spotId as spotId,c.contractDate as startDate,c.contractEndDate " +
            "as endDate,b.status as status) from User u inner join Book b on u.id=b.customerId inner join Contract c " +
            "on b.contractId=c.id inner join ContractContain cc on c.id=cc.contractId where u.id=?1 and b.isDel=false")
    Page<Map<String, Object>> findReserveMsgByUserId(Long userId, Pageable pageable);

    /**
     * 查询所有用户信息
     *
     * @return 所有用户信息
     */
    @Query("select new Map(u.id as userId,u.account as account,u.password as password,u.location as location,u.phone as phone,r.roleCode as roleCode) from User u inner join RoleAccess r on u.id=r.userId")
    List<Map<String, Object>> findAllUsers();

    /**
     * 根据角色代码查询用户信息
     *
     * @param roleCode 角色代码
     * @return 用户信息列表
     */
    @Query("select new Map(u.id as userId,u.account as account,u.password as password,u.location as location) from User u inner join RoleAccess r on u.id=r.userId where r.roleCode=?1")
    List<Map<String,Object>> findUsersByRoleCode(String roleCode);

    /**
     * 根据账号查询用户
     *
     * @param account 账号
     * @param isDel 是否被删除
     * @return 用户
     */
    User findByAccountAndIsDel(String account, Boolean isDel);
}
